import Mock from 'mockjs'
import { usePostListStore } from '@/stores/post'
import { useUserListStore, useUserStore } from '@/stores/user'

Mock.mock('/post/add', 'post', (config) => {

    const req = JSON.parse(config.body)
    const post = usePostListStore()
    const userList = useUserListStore()
    const user = useUserStore()
    const postid = 'post' + String(Math.random()).slice(2)
    let thePost = {
        postText: req.postText,
        postid,
        userid: req.userid,
        img: req.img,
        time: (new Date()).toLocaleString(),
        topics: req.topics,
        comments: [],
        likes: [],
        collects: [],
    }
    post.addPost(thePost)
    userList.addPost({
        userid: req.userid,
        postid
    })
    user.changeUserInfo(userList.getUserInfo(req.userid))

    return {
        code: '200',
        message: '发布成功',
        data: {
            post: thePost,
        }
    }
})

Mock.mock('/post/addComment', 'post', (config) => {

    const req = JSON.parse(config.body)
    const post = usePostListStore()
    const userList = useUserListStore()
    const user = useUserStore()
    let commentid = 'comment' + String(Math.random()).slice(2)
    const data = {
        postid: req.postid,
        data: {
            commentid,
            text: req.text,
            userid: req.userid,
            date: req.date
        }
    }

    post.addComment(data)
    userList.addComment({
        userid: post.getPost(req.postid).userid,
        data: {
            userid: req.userid,
            postid: req.postid,
            commentid,
        }
    })
    user.changeUserInfo(userList.getUserInfo(req.userid))

    return {
        code: '200',
        message: '发布成功',
        data: {
            post: post.getPost(req.postid)
        }
    }
})

Mock.mock('/post/like', 'post', (config) => {
    const req = JSON.parse(config.body)
    const user = useUserStore()
    const data = {
        code: '200',
        message: '你已经点过赞了',
    }
    const userList = useUserListStore()
    const post = usePostListStore()
    if (req.userid == req.postUserid) {
        data.message = '不能给自己点赞'
        return data
    }
    userList.addLike(req)
    const flag = post.addlike(req)
    if (flag) {
        data.message = '点赞成功'
    }
    user.changeUserInfo(userList.getUserInfo(req.userid))
    return data
})

Mock.mock('/post/collect', 'post', (config) => {
    const req = JSON.parse(config.body)
    const post = usePostListStore()
    const userList = useUserListStore()
    const user = useUserStore()
    const data = {
        code: '200',
        message: '已经在收藏夹中'
    }
    if (req.userid == req.postUserid) {
        data.message = '不能收藏自己的帖子'
    } else {
        const flag = post.addCollect(req)
        userList.addCollect(req)
        user.changeUserInfo(userList.getUserInfo(req.userid))
        if (flag) {
            data.message = '收藏成功'
        }
    }
    return data
})